<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="110px"
    >
      <el-row>
        <el-col :span="10">
          <el-form-item label="房型编码" prop="rpCode">
            <el-input v-model="dataForm.rpCode" placeholder="房型编码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="RP名称" prop="rpName">
            <el-input v-model="dataForm.rpName" placeholder></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="房态" prop="roomStatus">
            <el-switch v-model="dataForm.roomStatus" :active-value="1" :inactive-value="2"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上传状态" prop="status">
            <el-switch v-model="dataForm.status" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" prop="isPhone">
            <el-switch v-model="dataForm.isPhone" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="人工校准" prop="isCorrect">
            <el-switch v-model="dataForm.isCorrect" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="早餐个数" prop="breakfastNum">
        <el-input v-model="dataForm.breakfastNum" placeholder="早餐个数"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="18">
          <el-form-item label="退订政策" prop="cancelPolicy">
            <el-radio-group @change="changePolicy" v-model="dataForm.cancelPolicy">
              <el-radio :label="1">任意退</el-radio>
              <el-radio :label="2">不能退</el-radio>
              <el-radio :label="4">条件退</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button v-if="addPoliceVisible" type="primary" @click="addPolice()">增加</el-button>
        </el-col>
      </el-row>
      <el-form-item label-width="0" v-if="addPoliceVisible">
        <el-table :data="dataCancelPolice" border style="width: 100%">
          <el-table-column prop="pId" header-align="center" align="center" label="序号"></el-table-column>
          <el-table-column prop="preHour" header-align="center" align="center" label="提前X小时前退订">
            <template slot-scope="scope">
              <el-input v-model="scope.row.preHour" placeholder="提前X小时前退订"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="fine" header-align="center" label="扣除Y%的罚金" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fine" placeholder="扣除Y%的罚金"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="removePolice(scope.row.pId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="最小提前预定" prop="minHours">
            <el-input v-model="dataForm.minHours" placeholder="最小提前预定小时"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大提前预定" prop="maxHours">
            <el-input v-model="dataForm.maxHours" placeholder="最大提前预定小时"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="最小连住" prop="minDays">
            <el-input v-model="dataForm.minDays" placeholder="最小连住天数"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大连住" prop="maxDays">
            <el-input v-model="dataForm.maxDays" placeholder="最大连住天数"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="销售渠道" prop="channel">
        <el-checkbox-group v-model="channels" @change="chanChange">
          <el-checkbox label="H">飞猪</el-checkbox>
          <el-checkbox label="O">钉钉商旅</el-checkbox>
          <el-checkbox label="A">集团内部商旅</el-checkbox>
          <el-checkbox label="M">无线专享价</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="平均价格" prop="avgPrice">
            <el-input v-model="dataForm.avgPrice" placeholder="平均价格"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="市场价格" prop="marketPrice">
            <el-input v-model="dataForm.marketPrice" placeholder="市场价格"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="设施服务" prop="services">
        <el-input type="textarea" :rows="2" v-model="dataForm.services" placeholder="设施服务"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="有效期始" prop="startDate">
            <el-date-picker
              v-model="dataForm.startDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              style="width:100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期止" prop="endDate">
            <el-date-picker
              v-model="dataForm.endDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              style="width:100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="每天生效时间" prop="startTime">
            <el-time-select
              style="width:100%"
              v-model="dataForm.startTime"
              :picker-options="{
              start: '00:00',
              step: '00:15',
              end: '12:00'
            }"
              placeholder="选择时间"
            ></el-time-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="每天失效时间" prop="endTime">
            <el-time-select
              style="width:100%"
              v-model="dataForm.endTime"
              :picker-options="{
              start: '22:00',
              step: '00:15',
              end: '24:00'
            }"
              placeholder="选择时间"
            ></el-time-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="数据来源" prop="cancelPolicyFrom">
        <el-radio-group v-model="dataForm.cancelPolicyFrom">
          <el-radio label="1">携程</el-radio>
          <el-radio label="2">美团</el-radio>
          <el-radio label="3">官网</el-radio>
          <el-radio label="4">其他</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      addPoliceVisible: false,
      channels: [],
      pId: 1,
      dataCancelPolice: [],
      dataForm: {
        id: 0,
        rpCode: '',
        hotelCode: '',
        roomCode: '',
        rpName: '',
        isPhone: '',
        isCorrect: 0,
        roomStatus: '',
        rpType: '',
        verifyType: '',
        avgPrice: '',
        marketPrice: '',
        isThree: '',
        breakfastNum: '',
        paymentType: '',
        minDays: '',
        maxDays: '',
        minHours: '',
        maxHours: '',
        services: '',
        startDate: '',
        endDate: '',
        startTime: '',
        endTime: '',
        guaranteeRule: '',
        cancelPolicy: '',
        cancelPolicyFrom: '',
        status: '',
        type: '',
        minAmount: '',
        enName: '',
        channel: '',
        breakfastCal: '',
        cancelPolicyCal: '',
        canCheckoutEnd: ''
      },
      dataRule: {
        rpCode: [
          { required: true, message: '房型编码不能为空', trigger: 'blur' }
        ],
        rpName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    changePolicy(value) {
      if (value === 4) {
        this.addPoliceVisible = true
        if (this.dataCancelPolice.length <= 0) {
          this.dataCancelPolice.push({ "pId": this.pId, "preHour": 24, "fine": 10 })
        }
        this.resetCancePoliceId()
      } else {
        this.addPoliceVisible = false
      }
    },
    addPolice() {
      this.dataCancelPolice.push({ "pId": this.pId, "preHour": 24, "fine": 10 })
      this.resetCancePoliceId()
    },
    chanChange(value) {
      if (value === null) {
        this.dataForm.channel = null
      }
      this.dataForm.channel = value.reduce((preValue, curValue) => {
        return preValue + "," + curValue
      })
    },
    removePolice(pId) {
      if (this.dataCancelPolice.length <= 1) {
        this.$alert('至少需要有一个退订政策', '提示', {
          confirmButtonText: '确定',
          callback: action => { }
        });
        return
      }
      let arr = this.dataCancelPolice
      arr.splice(arr.findIndex(item => item.pId === pId), 1)
      this.resetCancePoliceId()
    },
    resetCancePoliceId() {
      this.pId = this.dataCancelPolice.length + 1
      let arr = this.dataCancelPolice
      arr.map((value, index, array) => {
        value.pId = index + 1
      })
    },
    tranCancelPolice(value) {
      let policy = null
      try {
        if (value != null || value != undefined) {
          let p = JSON.parse(value)
          policy = p.cancelPolicyType
          if (policy === 4) {
            this.addPoliceVisible = true
            let pInfo = p.policyInfo
            Object.keys(pInfo).map(key => {
              this.dataCancelPolice.push({ "pId": this.pId, "preHour": key, "fine": pInfo[key] })
              this.pId = this.dataCancelPolice.length + 1
            })
          }else{
            this.addPoliceVisible = false
          }
        }
      } catch (err) {
        policy = null
        return policy
      }
      return policy
    },
    init(id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.dataForm.cancelPolicy = 1
      this.addPoliceVisible = false
      this.dataCancelPolice = []
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/ht/htlogicroom/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.rpCode = data.htLogicRoom.rpCode
              this.dataForm.hotelCode = data.htLogicRoom.hotelCode
              this.dataForm.roomCode = data.htLogicRoom.roomCode
              this.dataForm.rpName = data.htLogicRoom.rpName
              this.dataForm.isPhone = data.htLogicRoom.isPhone
              this.dataForm.isCorrect = data.htLogicRoom.isCorrect
              this.dataForm.roomStatus = data.htLogicRoom.roomStatus
              this.dataForm.rpType = data.htLogicRoom.rpType
              this.dataForm.verifyType = data.htLogicRoom.verifyType
              this.dataForm.avgPrice = data.htLogicRoom.avgPrice
              this.dataForm.marketPrice = data.htLogicRoom.marketPrice
              this.dataForm.isThree = data.htLogicRoom.isThree
              this.dataForm.breakfastNum = data.htLogicRoom.breakfastNum
              this.dataForm.paymentType = data.htLogicRoom.paymentType
              this.dataForm.minDays = data.htLogicRoom.minDays
              this.dataForm.maxDays = data.htLogicRoom.maxDays
              this.dataForm.minHours = data.htLogicRoom.minHours
              this.dataForm.maxHours = data.htLogicRoom.maxHours
              this.dataForm.services = data.htLogicRoom.services
              this.dataForm.startDate = data.htLogicRoom.startDate
              this.dataForm.endDate = data.htLogicRoom.endDate
              this.dataForm.startTime = data.htLogicRoom.startTime
              this.dataForm.endTime = data.htLogicRoom.endTime
              this.dataForm.guaranteeRule = data.htLogicRoom.guaranteeRule
              this.dataForm.cancelPolicy = this.tranCancelPolice(data.htLogicRoom.cancelPolicy)
              this.dataForm.cancelPolicyFrom = data.htLogicRoom.cancelPolicyFrom
              this.dataForm.status = data.htLogicRoom.status
              this.dataForm.type = data.htLogicRoom.type
              this.dataForm.minAmount = data.htLogicRoom.minAmount
              this.dataForm.enName = data.htLogicRoom.enName
              this.dataForm.channel = data.htLogicRoom.channel
              this.channels = this.dataForm.channel === null || this.dataForm.channel === undefined ? [] : this.dataForm.channel.split(',')
              this.dataForm.breakfastCal = data.htLogicRoom.breakfastCal
              this.dataForm.cancelPolicyCal = data.htLogicRoom.cancelPolicyCal
              this.dataForm.canCheckoutEnd = data.htLogicRoom.canCheckoutEnd
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let police = this.dataForm.cancelPolicy
          let strPolice = null
          let strPinfo = ""
          switch (police) {
            case 1:
            case 2:
              strPolice = '{"cancelPolicyType":' + police + '}'
              break
            case 4:
              strPolice = '{"cancelPolicyType":4,"policyInfo":{'
              strPinfo = this.dataCancelPolice.reduce((preValue, curValue, index) => {
                return preValue + '"' + curValue.preHour + '":' + curValue.fine + ","
              }, "")
              strPolice = strPolice + strPinfo
              let reg = /,$/gi
              strPolice = strPolice.replace(reg, "}}")
              break
          }
          this.$http({
            url: this.$http.adornUrl(`/ht/htlogicroom/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'rpCode': this.dataForm.rpCode,
              'hotelCode': this.dataForm.hotelCode,
              'roomCode': this.dataForm.roomCode,
              'rpName': this.dataForm.rpName,
              'isPhone': this.dataForm.isPhone,
              'isCorrect': this.dataForm.isCorrect,
              'roomStatus': this.dataForm.roomStatus,
              'rpType': this.dataForm.rpType,
              'verifyType': this.dataForm.verifyType,
              'avgPrice': this.dataForm.avgPrice,
              'marketPrice': this.dataForm.marketPrice,
              'isThree': this.dataForm.isThree,
              'breakfastNum': this.dataForm.breakfastNum,
              'paymentType': this.dataForm.paymentType,
              'minDays': this.dataForm.minDays,
              'maxDays': this.dataForm.maxDays,
              'minHours': this.dataForm.minHours,
              'maxHours': this.dataForm.maxHours,
              'services': this.dataForm.services,
              'startDate': this.dataForm.startDate,
              'endDate': this.dataForm.endDate,
              'startTime': this.dataForm.startTime,
              'endTime': this.dataForm.endTime,
              'guaranteeRule': this.dataForm.guaranteeRule,
              'cancelPolicy': strPolice,
              'cancelPolicyFrom': this.dataForm.cancelPolicyFrom,
              'status': this.dataForm.status,
              'type': this.dataForm.type,
              'minAmount': this.dataForm.minAmount,
              'enName': this.dataForm.enName,
              'channel': this.dataForm.channel,
              'breakfastCal': this.dataForm.breakfastCal,
              'cancelPolicyCal': this.dataForm.cancelPolicyCal,
              'canCheckoutEnd': this.dataForm.canCheckoutEnd
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
